﻿using Hangfire.Annotations;
using Hangfire.Dashboard;
using System;
using System.Collections.Generic;

namespace lhservice.common.hangfire
{
  public class HangfireAuthorizationFilter : IDashboardAuthorizationFilter
  {
    private string key;
    private string _auth;
    private TimeSpan _span;
    public static Dictionary<string, DateTime> LoginIPAddressList = new Dictionary<string, DateTime>();
    public HangfireAuthorizationFilter(string auth, string urlKey, TimeSpan span)
    {
      key = urlKey;
      _auth = auth;
      _span = span;
    }
    public bool Authorize([NotNull] DashboardContext context)
    {
      if (ExitIp(context.Request.RemoteIpAddress))
        return true;
      string auth = context.Request.GetQuery(key);
      if (_auth == auth)
      {
        LoginIPAddressList.TryAdd(context.Request.RemoteIpAddress, DateTime.Now.Add(_span));
        return true;
      }
      context.Response.ContentType = "text/plain; charset=utf-8";
      context.Response.StatusCode = 404;
      context.Response.WriteAsync("页面不存在");
      return false;
    }
    public bool ExitIp(string ip)
    {
      if (!LoginIPAddressList.ContainsKey(ip))
        return false;
      DateTime dateTime = LoginIPAddressList.GetValueOrDefault(ip);
      if (dateTime < DateTime.Now)//过期
      {
        LoginIPAddressList.Remove(ip);
        return false;
      }
      return true;
    }
    public static HangfireAuthorizationFilter Create(string auth, string urlKey = "auth", TimeSpan? span = null)
    {
      if (span == null)
        span = TimeSpan.FromMinutes(20);
      return new HangfireAuthorizationFilter(auth, urlKey, span.Value);
    }
  }
}
